package app.fugema.shop.main.home.view;

import android.app.Application;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.appcompat.app.AlertDialog;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import app.fugema.shop.AndroidApp;
import app.fugema.shop.main.center.view.CollectProductActivity;
import app.fugema.shop.main.center.view.CollectShopActivity;
import app.fugema.shop.main.center.view.CouponListActivity;
import app.fugema.shop.main.center.view.FootMarkActivity;
import app.fugema.shop.main.center.view.UserMoneyActivity;
import app.fugema.shop.main.evaluate.view.MyQAActivity;
import app.fugema.shop.main.invoice.view.IntegralRecordActivity;
import app.fugema.shop.main.order.view.AddressManageActivity;
import app.fugema.shop.main.order.view.OrderAfterSaleListActivity;
import app.fugema.shop.main.order.view.OrderListActivity;
import app.fugema.shop.main.setting.model.EventMsg;
import app.fugema.shop.main.setting.view.SettingActivity;
import app.fugema.shop.main.setting.view.SysMsgActivity;

import com.base.common.app.AppManager;
import com.base.common.app.BaseConstant;
import com.base.common.app.LoginUtils;
import com.base.common.netBeanPackage.BaseApiResult;
import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.DensityUtil;
import com.base.common.utils.DialogUtils;
import com.base.common.utils.LogUtil;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.UIUtils;
import com.base.common.view.base.BaseFragment;
import com.base.common.viewmodel.BaseViewObserver;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;

import app.fugema.shop.R;
import app.fugema.shop.constants.PublicGlobal;
import app.fugema.shop.databinding.HomeMyCenterFragmentBinding;

import app.fugema.shop.main.home.vm.MyCenterVM;
import app.fugema.shop.main.login.model.MUserInfo;
import app.fugema.shop.main.order.view.GroupBookingListActivity;
import app.fugema.shop.util.PickerDialog;

public class HomeMyCenterFragment extends BaseFragment<HomeMyCenterFragmentBinding, MyCenterVM>
{
    @Override
    protected HomeMyCenterFragmentBinding initDataBinding(LayoutInflater inflater, ViewGroup container)
    {
        return DataBindingUtil.inflate(inflater, R.layout.home_my_center_fragment, container, false);
    }

    //private GeneralRecyclerAdapter adapter;
    private PickerDialog logoutPicker;

    @Override
    protected void initNotificationReceipt()
    {
        super.initNotificationReceipt();
        LiveEventBus.get(BaseConstant.EventKey.USER_UPDATE_SUCCESS, MUserInfo.class).observe(this,(mUserInfo)->{
                loginChecked();
            // 切换登录的时候 重新设置别名
            if(((MainActivity)getActivity()).isCanAlias)
            {
                PushAgent.getInstance(getActivity()).setAlias(String.valueOf(mUserInfo.getUserId()), "uid", new UTrack.ICallBack() {
                    @Override
                    public void onMessage(boolean b, String s)
                    {
                        LogUtil.e("UPush","Alias result = "+s);
                        getActivity().runOnUiThread( ()->{

                            viewModel.setUesrDeviceToken( mUserInfo.getUserId(),PublicGlobal.getDeviceToken() )
                                    .observe(HomeMyCenterFragment.this, new BaseViewObserver<LiveDataWrapper<BaseApiResult>>() {
                                        @Override
                                        protected void onSuccess(LiveDataWrapper<BaseApiResult> data)
                                        {

                                        }
                                    });
                        } );
                    }
                });
            }
            }
        );

        LiveEventBus.get(BaseConstant.EventKey.LOGIN_OUT_ONCLICK).observe(this, new Observer<Object>()
        {
            @Override
            public void onChanged(Object data)
            {
                loginChecked();
            }
        });
    }


    private void loginChecked()
    {
        if (LoginUtils.isLogin())
        {
            binding.tvVIP.setVisibility(View.VISIBLE);
            PublicGlobal.initUserInfo();
            MUserInfo userBean = PublicGlobal.getUserInfo();
            if (userBean != null)
            {
                binding.tvName.setText(userBean.getUserName());
                if( UIUtils.isNotEmpty( userBean.getPhoto() ) )
                {
                    binding.givHeadImage.loadUrl(userBean.getPhoto());
                }

                binding.tvCollectProductCount.setText( ""+ userBean.getFavoriteProduct() );
                binding.tvCollectShopCount.setText(""+userBean.getFavoriteShop());
            }
            binding.tvBtnLogout.setVisibility(View.VISIBLE);
            String userKey = LoginUtils.getToken();
            viewModel.refreshUserInfo( userKey )
                     .observe(getLifecycleOwner(), new BaseViewObserver<LiveDataWrapper<MUserInfo>>() {
                         @Override
                         protected void onSuccess(LiveDataWrapper<MUserInfo> data)
                         {
                               if( data.data.isSuccess() )
                               {
                                   PublicGlobal.setUserInfo(data.data);
                                   //刷新 订单数量
                                   initOrderCount(data.data);
                               }
                         }
                     });

        }
        else
        {
            binding.tvName.setText("立即登录");
            binding.tvVIP.setVisibility(View.GONE);
            binding.givHeadImage.setImageResource(R.drawable.ic_def_bg);
            binding.tvBtnLogout.setVisibility(View.INVISIBLE);
        }
    }


    @Override
    public void initView()
    {
        super.initView();
        int statusBarH = DensityUtil.getStatusBarHeight(getActivity());
        ViewGroup.LayoutParams layoutParams = (ViewGroup.LayoutParams) binding.statusBar.getLayoutParams();
        layoutParams.height = layoutParams.height + statusBarH;
        binding.statusBar.setLayoutParams( layoutParams );

        logoutPicker = new PickerDialog(getActivity(), (selectStr, position) -> {
            if( position == 0 )
            {
                //注销先退出登录
                if (LoginUtils.isLogin())
                {
                    new AlertDialog.Builder(getActivity())
                            .setTitle("提示")
                            .setMessage("当你注销“" + UIUtils.getString(R.string.app_name) + "”帐户后，我们将删除相应的信息?")
                            .setPositiveButton("确定",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which)
                                        {
                                            LoginUtils.loginOut();
                                            LiveEventBus.get(BaseConstant.EventKey.LOGIN_OUT_ONCLICK).post(-1);
                                        }
                                    })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).show();
                }

                //UIUtils.showToastSafes( selectStr );

            }
            else
            {
                //UIUtils.showToastSafes( selectStr );
                // 关闭当前应用

                DialogUtils.showSimpleDialog(getActivity(),false,(dialog,witch) ->{
                    AppManager.getInstance().removeAllActivity();
                },"确定要退出吗？");

            }
        });


        binding.setOnClickCheckedUtil(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {

                if (!LoginUtils.isLogin())
                {
                    //UIUtils.showToastSafes("未登录请登录");
                    LoginUtils.loginIn();
                    return;
                }

                switch (view.getId()) {
                    case R.id.llWaitPay:
                        OrderListActivity.start(getActivity(), 1);
                        break;
                    case R.id.llWaitSend:
                        OrderListActivity.start(getActivity(), 2);
                        break;
                    case R.id.llWaitAddressee:
                        OrderListActivity.start(getActivity(), 3);
                        break;
                    case R.id.llEvaluate:
                        OrderListActivity.start(getActivity(), 4);
                        break;
                    case R.id.llSales:
                        OrderAfterSaleListActivity.start(getActivity());
                        break;
                    case R.id.btnMyOrder:
                        OrderListActivity.start(getActivity(), 0);
                        break;
                    case R.id.btnMyWallet:
//                        UIUtils.showToastSafes(ChinaDate.getCurrentLunarDate());
                        break;
                    case R.id.btnMsg:
                        SysMsgActivity.start(getActivity());
                        break;
                    case R.id.tvName:
                    case R.id.givHeadImage:
                    case R.id.btnSetting:
                        SettingActivity.start(getActivity());
                        break;

                    case R.id.tv_collect_product_btn:
                        CollectProductActivity.start(getActivity());
                        break;
                    case R.id.tv_collect_shop_btn:
                        CollectShopActivity.start(getActivity());
                        break;
                    case R.id.llToolsGroupBooking:
                        //我的拼团
                        GroupBookingListActivity.start(getActivity());
                        break;
                    case R.id.llToolsAddress:
                        //收货地址
                        AddressManageActivity.start(getActivity(), false);
                        break;
                    case R.id.ll_btn_coupon:
                        //UIUtils.showToastSafes("优惠券");
                        //优惠券
                        CouponListActivity.start(getActivity());
                        break;
                    case R.id.ll_my_jifen:
                        //我的积分
                        IntegralRecordActivity.start(view.getContext() , PublicGlobal.getUserInfo().getIntegral() );
                        break;
                    case R.id.ll_my_foot:
                        //足迹
                        FootMarkActivity.start(getActivity());
                        break;
                    case R.id.ll_my_money:
                        //我的钱包
                        UserMoneyActivity.start(getActivity());
                        break;
                    case R.id.ll_my_asks:
                        MyQAActivity.start(getActivity());
                        break;
                    case R.id.tv_btn_logout:
                        logoutPicker.showPickContentNoTitle( new String[]{ "注销当前账号" ,"直接关闭应用" } );

                        break;

                }
            }
        });

        loginChecked();

        //暂时 未接入 通信  去掉msg
        binding.btnMsg.setVisibility(View.INVISIBLE);

    }


    @Override
    public void onUserVisible() {
        super.onUserVisible();
        //initOrderCount();
        loginChecked();
    }

    @Override
    public void onPauseRevert() {
        super.onPauseRevert();

        loginChecked();
    }


    private void initOrderCount(MUserInfo mUserBean)
    {
        binding.tvName.setText(mUserBean.getUserName());
        if( UIUtils.isNotEmpty( mUserBean.getPhoto() ) )
        {
            binding.givHeadImage.loadUrl(mUserBean.getPhoto());
        }

        //查询 各状态订单数量  ？
        /*
            * WaitingForPay : 0
            * WaitingForDelivery : 0
            * WaitingForComments : 0
            * WaitingForRecieve : 0
            * RefundOrders : 0
            */
        if( mUserBean.getWaitingForPay() != 0 )
        {
            binding.rtvOrderWaitPayCount.setVisibility(View.VISIBLE);
            binding.rtvOrderWaitPayCount.setText(String.valueOf(mUserBean.getWaitingForPay()));
        }
        else
        {
            binding.rtvOrderWaitPayCount.setVisibility(View.GONE);
        }

        if( mUserBean.getWaitingForDelivery() != 0 )
        {
            binding.rtvOrderWaitSendCount.setVisibility(View.VISIBLE);
            binding.rtvOrderWaitSendCount.setText(String.valueOf(mUserBean.getWaitingForDelivery()));
        }
        else
        {
            binding.rtvOrderWaitSendCount.setVisibility(View.GONE);
        }

        if( mUserBean.getWaitingForRecieve() != 0 )
        {
            binding.rtvOrderWaitAddresseeCount.setVisibility(View.VISIBLE);
            binding.rtvOrderWaitAddresseeCount.setText(String.valueOf(mUserBean.getWaitingForRecieve()));
        }
        else
        {
            binding.rtvOrderWaitAddresseeCount.setVisibility(View.GONE);
        }

        if( mUserBean.getWaitingForComments() != 0 )
        {
            binding.rtvOrderWaitEvaluateCount.setVisibility(View.VISIBLE);
            binding.rtvOrderWaitEvaluateCount.setText(String.valueOf(mUserBean.getWaitingForComments()));
        }
        else
        {
            binding.rtvOrderWaitEvaluateCount.setVisibility(View.GONE);
        }


        if( mUserBean.getRefundOrders()!= 0 )
        {
            binding.rtvOrderSalesReturnCount.setVisibility(View.VISIBLE);
            binding.rtvOrderSalesReturnCount.setText(String.valueOf(mUserBean.getRefundOrders()));
        }
        else
        {
            binding.rtvOrderSalesReturnCount.setVisibility(View.GONE);
        }


    }


    @Override
    public void initData()
    {
        super.initData();
       // initOrderCount();
        //   去掉 推荐商品
        /*
        viewModel.getGoodsVM().getHomeGoodsByPage(1).observe(this, new BaseViewObserver<LiveDataWrapper<GoodsPageBean>>()
        {
            @Override
            protected void onSuccess(LiveDataWrapper<GoodsPageBean> data)
            {
                adapter.setDataList(data.data.getProduct());
            }

            @Override
            public boolean isEmptyData(LiveDataWrapper<GoodsPageBean> data)
            {
                return UIUtils.isEmpty(data.data.getProduct());
            }

            @Override
            protected void onEmptyLayout()
            {
                super.onEmptyLayout();
                binding.rtvTextView.setVisibility(View.GONE);
                //binding.rvRecyclerView.setVisibility(View.GONE);
            }
        });
        */
    }

}
